/*
 * @Author: chen17
 * @Date: 2022-06-21 14:30:11
 * @LastEditTime: 2022-10-12 10:43:18
 * @Description: 上传公用参数
 */

import { getQiNiuToken } from '@/api/common'

const state = {
    // 上传参数
    uploadToken: '',
    // token接口调用loading
    tokenLoading: false
}

const mutations = {
    set_upload_token(state, token) {
        state.uploadToken = token
    },
    set_token_loading(state, boo) {
        state.tokenLoading = boo
    }
}

const actions = {
    // 初始化上传token
    initUploadToken({ state, commit }) {
        return new Promise((resolve, rejetc) => {
            // 接口请求中 || 已获取
            if (state.tokenLoading || state.uploadToken) {
                resolve(true)
            } else {
                commit('set_token_loading', true)
                getQiNiuToken()
                    .then(res => {
                        commit('set_upload_token', res.data)
                        commit('set_token_loading', false)
                        resolve(true)
                    })
                    .catch(error => {
                        commit('set_upload_token', '')
                        commit('set_token_loading', false)
                        rejetc(error)
                    })
            }
        })
    },
    // 移除上传token
    removeUploadToken({ state, commit }) {
        if (state.uploadToken) commit('set_upload_token', '')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
